package router

import (
	"chat/global"
	"chat/internal/server"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"strconv"
)

var upGrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func Chat(c *gin.Context) {
	//升级get请求为webSocket协议
	user := c.Query("user")
	if user == "" {
		fmt.Println(user)
	}
	id, _ := strconv.Atoi(user)
	ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		global.Logger.Warnf("upGrader err: %+v", err)
		return
	}

	client := &server.Client{
		ID:   id,
		Send: make(chan []byte),
		Conn: ws,
	}
	server.MyServer.Register <- client
	go client.Read()
	go client.Write()
}
